var app = getApp();
var orderOffset;
var orderType, orderCode;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    iconwidth: 18,
    blankshow: false,
    blanktips: '没有订单记录',
    hasMore:true,
    orders: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    orderType = '1';
    orderCode = '';
    if (options.ordertype) {
      orderType = options.ordertype.toString();
      orderCode = options.ordercode;
    }
    this.setData({
      orderstatus: orderType
    });
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var cancel_w = 0;
        var search_all = res.windowWidth - 20;
        var icon_w = 18;
        var scroll_h = res.windowHeight - 40;
        // var scroll_h = res.windowHeight - 46 - 40;  // 加入搜索框的高度
        that.setData({
          cancelshow: false,
          cancelwidth: cancel_w,
          searchwidth: search_all,
          iconwidth: icon_w,
          scrollheight: scroll_h
        });
      },
    });
    orderOffset = 0;
    // this.loadOrderList(orderOffset, orderCode);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadOrderList(orderOffset, orderCode);
  },
  //  加载订单
  loadOrderList: function (offset, ordertype = '') {
    app.showLoading();
    var url = '/index.php/api/Order/order_list';
    var params = {
      'type': ordertype,
      'page': offset
    };
    app.request(url, params).then(this.orderListCallBack.bind(this))
  },
  orderListCallBack: function (res) {
    app.hideLoading();
    console.log(res);
    if (res.status != 'ok') {
      this.setData({
        blankshow: true
      });
      return;
    }
    var tmp_orders = res.result;
    if (tmp_orders.length <= 0) {
      if (orderOffset == 0) {
        this.setData({
          blankshow: true,
          hasMore: false
        });
      }
      else {
        this.setData({
          hasMore: false
        });
      }
      return;
    }
    if (tmp_orders.length < 10) {
      this.setData({
        hasMore: false
      });
    }
    else {
      this.setData({
        hasMore: true
      });
    }
    var orders = [];
    if (orderOffset > 0) {
      orders = this.data.orders;
    }
    for (var i = 0; i < tmp_orders.length; i++) {
      var orderinfo = {};
      orderinfo.order_id = tmp_orders[i].order_id;
      orderinfo.order_sn = tmp_orders[i].order_sn;
      orderinfo.price = tmp_orders[i].order_amount;
      orderinfo.express = tmp_orders[i].shipping_price;
      orderinfo.status = tmp_orders[i].order_status_desc;
      orderinfo.statusCode = tmp_orders[i].order_status_code;
      orderinfo.orderdate = app.formatDateTime(tmp_orders[i].add_time);
      orderinfo.totalcount = tmp_orders[i].count_goods_num;
      orderinfo.order_amount = tmp_orders[i].order_amount;
      orderinfo.shipping_code = tmp_orders[i].shipping_code;
      if (tmp_orders[i].invoice_no) {
        orderinfo.invoice_no = tmp_orders[i].invoice_no;
      }
      else {
        orderinfo.invoice_no = '';
      }

      orderinfo.pay_btn = tmp_orders[i].pay_btn;
      orderinfo.cancel_btn = tmp_orders[i].cancel_btn;
      orderinfo.receive_btn = tmp_orders[i].receive_btn;
      orderinfo.comment_btn = tmp_orders[i].comment_btn;
      orderinfo.shipping_btn = tmp_orders[i].shipping_btn;
      orderinfo.return_btn = tmp_orders[i].return_btn;
      var goodslist = [];
      var gNames = [];
      for (var j = 0; j < tmp_orders[i].goods_list.length; j++) {
        var goodsinfo = {};
        goodsinfo.name = tmp_orders[i].goods_list[j].goods_name;
        goodsinfo.dprice = tmp_orders[i].goods_list[j].goods_price;
        goodsinfo.oprice = tmp_orders[i].goods_list[j].market_price;
        goodsinfo.mprice = tmp_orders[i].goods_list[j].member_goods_price;
        goodsinfo.buycount = tmp_orders[i].goods_list[j].goods_num;
        goodsinfo.icon = app.globalData.webUrl + tmp_orders[i].goods_list[j].original_img;
        gNames.push(goodsinfo.name);
        var standard = [];
        if (tmp_orders[i].goods_list[j].spec_key_name) {
          if (tmp_orders[i].goods_list[j].spec_key_name != '') {
            standard = tmp_orders[i].goods_list[j].spec_key_name.split(' ');
            for (var k = 0; k < standard.length; k++) {
              standard[k] = standard[k].split(':')[1];
            }
          }
        }
        goodsinfo.standard = standard;
        goodslist.push(goodsinfo);
      }
      orderinfo.gnames = gNames.join(',');
      orderinfo.goodslist = goodslist;
      orders.push(orderinfo);
    }
    var blankshow = true;
    if (orders.length > 0) {
      blankshow = false;
    }
    this.setData({
      blankshow: blankshow,
      orders: orders
    });
  },
  //  加载更多订单
  loadMoreOrders: function () {
    if (this.data.hasMore == false) {
      return;
    }
    orderOffset++;
    this.loadOrderList(orderOffset, orderCode);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareToIndex();
  },
  doInputAction: function () {
    this.setData({
      cancelwidth: 40,
      cancelshow: true
    });
  },
  didInputAction: function () {
    this.setData({
      cancelwidth: 0,
      cancelshow: false
    });
  },
  doSearchAction: function (event) {
    var searchkey = event.detail.value;
  },
  changeOrderStatus: function (event) {
    orderType = event.currentTarget.dataset.orderstatus;
    this.setData({
      orderstatus: orderType,
      scrolltop: 0
    });
    orderOffset = 0;
    if (orderType.toString() == '2') {
      orderCode = 'WAITPAY';
    }
    else if (orderType.toString() == '3') {
      orderCode = 'WAITSEND';
    }
    else if (orderType.toString() == '5') {
      orderCode = 'FINISH';
    }
    else if (orderType.toString() == '1') {
      orderCode = '';
    }
    app.showLoading();
    this.loadOrderList(orderOffset, orderCode);
  },
  showOrderDetail: function (event) {
    var orderid = event.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: './orderdetail/orderdetail?orderid=' + orderid,
    })
  },
  dealOrder: function (event) {
    var dealtype = event.currentTarget.dataset.dealtype;
    var orderinfo = event.currentTarget.dataset.orderinfo; 
    // console.log(orderinfo);
    var that = this;
    if (dealtype == 'comment') {
      wx.navigateTo({
        url: '../comment/comment?goods=' + JSON.stringify(orderinfo),
      });
    }
    else if (dealtype == 'pay') {
      wx.navigateTo({
        url: './payorder/payorder?order=' + JSON.stringify(orderinfo),
      });
    }
    else if (dealtype == 'cancel') {
      if (orderinfo.statusCode == 'WAITSEND') {
        wx.navigateTo({
          url: './cancelafterpay/cancelafterpay?order=' + JSON.stringify(orderinfo),
        });
        return;
      }
      wx.showModal({
        title: '提示',
        content: '确定取消该订单吗',
        success: function (res) {
          if (res.confirm) {
            that.updateOrder(orderinfo.order_id, 'cancel');
          }
        }
      });
    }
    else if (dealtype == 'express') {
      wx.navigateTo({
        url: './express/express?shippingcode=' + orderinfo.shipping_code + '&invoiceno=' + orderinfo.invoice_no,
      });
    }
    else if (dealtype == 'receive') {
      wx.showModal({
        title: '提示',
        content: '确定收货吗',
        success: function (res) {
          if (res.confirm) {
            that.updateOrder(orderinfo.order_id, 'receive');
          }
        }
      });
    }
  },
  updateOrder: function (orderid, dtype) {
    var url = '';
    if (dtype == 'cancel') {
      url = '/index.php/api/Order/cancel_order';
    }
    else if (dtype == 'receive') {
      url = '/index.php/api/Order/order_confirm';
    }
    var params = {
      id: orderid
    };
    app.request(url, params).then(this.updateOrderCallBack.bind(this))
  },
  updateOrderCallBack: function (res) {
    wx.showToast({
      title: res.msg,
      icon: 'none'
    });
    if (res.status == 'ok') {
      app.showLoading();
      orderOffset = 0;
      this.loadOrderList(orderOffset, orderCode);
    }
  },
  searchOrder: function () {
    wx.navigateTo({
      url: '../store/search/search?target=order',
    });
  }
})